package com.jwgf.smarowindingmachine_unity.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.DialogFragment;

import com.jwgf.adapter.CommonAdapter;
import com.jwgf.adapter.ViewHolder;
import com.jwgf.smarowindingmachine_unity.R;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileSelectedDialog extends DialogFragment {
    public static final String ROOT_PATH = "root";
    private static final String NAME = "name";
    private static final String PATH = "path";

    private AlertDialog dlg;
    private Runnable callback;
    private ListView listView;
    private CommonAdapter adapter;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String rootDir;
    private String curDir;
    private String selectedPath;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bd = getArguments();
        rootDir = bd.getString(ROOT_PATH);
        curDir = rootDir;

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.list_view, null);
        listView = (ListView) v.findViewById(R.id.list);
        listView.setDescendantFocusability(ListView.FOCUS_AFTER_DESCENDANTS);
        listView.setAdapter(
                adapter = new CommonAdapter<Map<String, Object>>(getActivity(), getData(rootDir), R.layout.item_file) {

                    @Override
                    public void convert(ViewHolder holder, Map<String, Object> item) {
                        File file = new File((String) item.get(PATH));
                        if (file.isFile()) {
                            holder.setImageResource(R.id.img, R.drawable.file);
                        } else {
                            holder.setImageResource(R.id.img, R.drawable.folder);
                        }
                        holder.setText(R.id.name, (String) item.get(NAME));
                        holder.setText(R.id.path, (String) item.get(PATH));
                    }
                });

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                selectedPath = (String) list.get(position).get(PATH);
            }
        });

        listView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (new File((String) list.get(position).get(PATH)).isDirectory()) {
                    curDir = (String) list.get(position).get(PATH);
                    selectedPath = null;
                }
                getData(curDir);
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        builder.setTitle("选择文件");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (selectedPath == null) {
                    show(true);
                    Toast toast = Toast.makeText(getActivity(), "请选择路径！", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                } else {
                    show(false);
                }
                if (callback != null) {
                    new Handler(Looper.getMainLooper()).post(callback);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                show(false);
            }
        });
        builder.setNeutralButton("返回上一级", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                show(true);
                if (!curDir.equals(rootDir)) {
                    curDir = new File(curDir).getParent();
                    getData(curDir);
                    adapter.notifyDataSetChanged();
                }

            }
        });
        builder.setView(v);
        dlg = builder.create();

        return dlg;
    }

    @Override
    public void onResume() {
        super.onResume();
        getDialog().getWindow().setLayout(800, 480);
    }

    public void setCallBack(Runnable callback) {
        this.callback = callback;
    }

    public String getPath() {
        return selectedPath;
    }

    private List<Map<String, Object>> getData(String path) {
        File dir = new File(path);
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            list.clear();
            for (File file : files) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put(NAME, file.getName());
                map.put(PATH, file.getAbsolutePath());
                list.add(map);
            }
        }
        return list;
    }

    private void show(boolean isShow) {
        try {
            Field field = dlg.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dlg, !isShow);
            dlg.dismiss();

        } catch (Exception e) {

        }
    }

}
